package com.link.base.wechat.basic.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.link.core.cllog.LCLogger;
import com.link.core.util.HttpRequestUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * link http请求工具类
 *
 * @author lujiang
 * @date  2019-03-07
 */
public class WeixinHttpUtil {

    /**
     * 描述: 发起https请求并获取结果
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(HttpRequestUtil.jsonRequest(requestUrl, outputStr, requestMethod));
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return jsonObject;
    }

    /**
     * 2.发起POST请求
     * @param url  请求url
     * @param data 请求参数（json）
     * @return
     * @throws Exception JSONObject
     * @desc ：
     */
    public static JSONObject doPost(String url, Object data) throws Exception {
        //1.生成一个请求
        HttpPost httpPost = new HttpPost(url);

        //2.配置请求属性
        //2.1 设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
        httpPost.setConfig(requestConfig);
        //2.2 设置数据传输格式-json
        httpPost.addHeader("Content-Type", "application/json");
        //2.3 设置请求实体，封装了请求参数
        StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
        httpPost.setEntity(requestEntity);

        //3.发起请求，获取响应信息
        //3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            //3.3 发起请求，获取响应
            response = httpClient.execute(httpPost, new BasicHttpContext());
            int statusCode = 200;
            if (response.getStatusLine().getStatusCode() != statusCode) {

                return null;
            }
            //获取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

                //解析响应内容
                JSONObject result = JSON.parseObject(resultStr);
                String errcode = "errcode";
                if (result.getInteger(errcode) == null) {
                    return result;
                } else if (0 == result.getInteger(errcode)) {
                    return result;
                } else {
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new Exception("error code:" + errCode + ", error message:" + errMsg);
                }
            }
        } catch (IOException e) {
            LCLogger.withException(e);
        } finally {
            if (response != null) {
                try {
                    response.close();              //释放资源
                } catch (IOException e) {
                    LCLogger.withException(e);
                }
            }
        }
        return null;
    }

    /**
     * @param url
     * @return JSONObject
     * @throws Exception
     * @desc ：1.发起GET请求
     */
    public static JSONObject doGet(String url) throws Exception {

        //1.生成一个请求
        HttpGet httpGet = new HttpGet(url);
        //2.配置请求的属性
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
        httpGet.setConfig(requestConfig);

        //3.发起请求，获取响应信息
        //3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //3.2 发起请求，获取响应信息
            response = httpClient.execute(httpGet, new BasicHttpContext());

            //如果返回结果的code不等于200，说明出错了
            int statusCode = 200;
            if (response.getStatusLine().getStatusCode() != statusCode) {

                return null;
            }
            //4.解析请求结果
            //reponse返回的数据在entity中
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //将数据转化为string格式
                String resultStr = EntityUtils.toString(entity, "utf-8");
                //将String转换为 JSONObject
                JSONObject result = JSON.parseObject(resultStr);
                String errcode =  "errcode";
                if (result.getInteger(errcode) == null) {
                    return result;
                } else if (0 == result.getInteger(errcode)) {
                    return result;
                } else {
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new Exception("error code:" + errCode + ", error message:" + errMsg);
                }
            }
        } catch (IOException e) {
            LCLogger.withException(e);
        } finally {
            if (response != null) {
                try {
                    //释放资源
                    response.close();
                } catch (IOException e) {
                    LCLogger.withException(e);
                }
            }
        }

        return null;
    }

}
